package cron

import (
	"encoding/json"
	"time"

	"kop/libs/database"
	"kop/modules/island/configuration"
	"kop/modules/island/entity"
	"kop/modules/island/models"
	"kop/pb"

	awardM "kop/modules/award/models"
	guildC "kop/modules/guild/client"
	mailC "kop/modules/mail/client"
	serverC "kop/modules/server/client"
)

func Cron() {

	for range time.NewTicker(time.Hour * 24).C {

		var now = time.Now()
		if now.Weekday() == 0 && now.Hour() == 10 {

			SendAwards()

			// 周日10点发奖励
		} else if now.Weekday() == 0 && now.Hour() == 23 {

			database.DB.Exec("TRUNCATE TABLE island_guild_rankings")
		}
	}
}

// 发邮件
func SendAwards() {

	var p1 = &pb.Role{}

	var servers, _ = serverC.GetServers()
	for _, server := range servers {

		var configs = configuration.RankingAwardList
		var limit = configs[len(configs)-1].RankMax

		var ranking = models.GetServerRanking(server.ServerID, limit)

		for _, conf := range configs {

			var guildIDs = data(ranking).取对应排名的公会(conf.RankMax)

			for _, guildID := range guildIDs {

				var rank = data(ranking).排名(guildID)

				if members, err := guildC.Members(server.ServerID, guildID); err == nil {

					var IDs []int32
					for _, member := range members {
						if member.Position == pb.GuildPosition_President {

							var content, _ = json.Marshal(map[string]interface{}{"ID": 102, "s1": rank})
							_ = mailC.Send1(member.RoleID, "gonghui huizhang jiangli", string(content), awardM.RandAward(p1, conf.AwardID))
						} else {
							IDs = append(IDs, member.RoleID)
						}
					}

					var content, _ = json.Marshal(map[string]interface{}{"ID": 103, "s1": rank})
					_ = mailC.Send(IDs, "gonghui chengyuan jiangli", string(content), awardM.RandAward(p1, conf.AwardID))
				}
			}
		}
	}
}

type data []*entity.IslandGuildRanking

func (s data) 取对应排名的公会(confRank int) []int32 {

	var res []int32

	for k, v := range s {
		if k+1 <= confRank && !v.IsSend() {

			v.SetSend()
			res = append(res, v.GuildID)
		}
	}

	return res
}

func (s data) 排名(guildID int32) int {

	for k, v := range s {
		if v.GuildID == guildID {
			return k + 1
		}
	}

	return len(s) + 1
}
